<?php
	if(isset($_REQUEST['xml']) && ($_REQUEST['xml'] == '1')){
		$xml=1;
	}else{$xml=0;}
        session_start();
        if(session_is_registered(username)){
			$name=$_SESSION['username'];
        }else{
			//nao e preciso estar logged in
			$name="guest";
        }
        
		try{
			$db = new PDO('sqlite:../../projecto1.db');
        }
        catch(PDOException $err){
            if($xml==0){
			$error['Result'] = array('Recent'=>'DatabaseError');
			echo json_encode($error);
			die;
			}else{
				$doc = new DomDocument('1.0');
				$doc->formatOutput = TRUE;
				// create root node
				$root = $doc->createElement('Result');
				$root = $doc->appendChild($root);
				$attr = $doc->createAttribute("xmlns:xsi");
				$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
				$root->appendChild($attr);
				$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
				$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
				$root->appendChild($attr);
				//childs of root
				$error = $doc->createElement('Recent');
				$error= $root->appendChild($error);
				$value = $doc->createTextNode('DatabaseError');
				$value = $error->appendChild($value);
				echo $doc->saveXML();
			}
        }
        
        if(isset($_REQUEST['numero']) && $_REQUEST['numero'] != ""){
			$numero=$_REQUEST['numero'];
		}else{
			$numero =5;
		}
		
		//----------------------------------------------------------
		
	/*testes*/
	/*
		 echo "<br />test-link<br />idLink|linkURL|hits<br />";
		$test1 = $db->query('SELECT * FROM Link');
		foreach ($test1 as $r) {
			 echo ($r['idLink'] . " | " . $r['linkURL'] . " | "  . $r['hits'] . "<br />");
		}
		 echo "<br />test-tag<br />id|name<br />";
		$test2 = $db->query('SELECT * FROM Tag');
		foreach ($test2 as $r) {
			 echo ($r['idTag'] . " | " . $r['tagName'] . "<br />");
		}
		
		 echo "<br />test-user_link<br />idUserLink|idUser|idLink|shared|desc|title<br />";
		$test2 = $db->query('SELECT * FROM User_Link');
		foreach ($test2 as $r) {
			 echo ($r['idUserLink'] . " | " . $r['idUser']. " | ". $r['idLink']. " | ". $r['shared']. " | ". $r['description'] ." | " . $r['title']."<br />");
		}
		
		 echo "<br />test-user_link_tag<br />idUserLink|idTag<br />";
		$test2 = $db->query('SELECT * FROM User_Link_Tag');
		foreach ($test2 as $r) {
			 echo ($r['idUserLink'] . " | " . $r['idTag'] . "<br />");
		}
		//----------------------------------------------------------
        */
        $stmt = $db->prepare('SELECT * FROM User_Link ORDER BY idUserLink desc');       
        $stmt->execute();
        $user_link_list = $stmt->fetchAll();
        
        $contador=0;
        foreach ($user_link_list as $user_link) {
			if($contador < $numero){
				$stmt = $db->prepare('SELECT * FROM Link WHERE Link.idLink=:idlink');
				$stmt->bindParam(':idlink', $user_link['idLink']);
				$stmt->execute();
				$link = $stmt->fetch();
				
				$stmt = $db->prepare('SELECT * FROM User_Link_Tag WHERE User_Link_Tag.idUserLink=:iduserlink');
				$stmt->bindParam(':iduserlink', $user_link['idUserLink']);
				$stmt->execute();
				$tags = $stmt->fetchAll();				
				
				$json['Result']['Recent'][$contador] = array('title'=>$user_link['title'],
				'linkURL'=>$link['linkURL'],'description'=>$user_link['description'],'hits'=>$link['hits']);
                        
				$posicaoarray=0;
				if(!$tags){
					$array = array();
				}else{
					$array = array();
					foreach ($tags as $tag){
						$stmt = $db->prepare('SELECT * FROM Tag WHERE Tag.idTag=:idTag');
						$idTag = $tag['idTag'];
						$stmt->bindParam(':idTag', $idTag);
						$stmt->execute();
						$tag_name = $stmt->fetch();
						$array[$posicaoarray]=$tag_name['tagName'];
						$posicaoarray++;
					}
				}
                        
				$json['Result']['Recent'][$contador]['tags']=$array;
				$contador++;
			}
		}
               
	if($xml==0){
		echo json_encode($json);
		die;
	}else{
		$doc = new DomDocument('1.0');
		$doc->formatOutput = TRUE;
		// create root node
		$root = $doc->createElement('Result');
		$root = $doc->appendChild($root);
		$attr = $doc->createAttribute("xmlns:xsi");
		$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
		$root->appendChild($attr);
		$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
		$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
		$root->appendChild($attr);
		$popular = $doc->createElement('Recent');
		$error= $root->appendChild($popular);
		//childs of root
		foreach($json as $j){
			foreach($j as $k){
				foreach($k as $l){
					$link = $doc->createElement('Link');
					$error= $popular->appendChild($link);
					
					$link_title = $doc->createElement('Title');
					$error= $link->appendChild($link_title);
					$value = $doc->createTextNode($l['title']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$link_url = $doc->createElement('LinkURL');
					$error= $link->appendChild($link_url);
					$value = $doc->createTextNode($l['linkURL']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$link_desc = $doc->createElement('Description');
					$error= $link->appendChild($link_desc);
					$value = $doc->createTextNode($l['description']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$link_hits = $doc->createElement('Hits');
					$error= $link->appendChild($link_hits);
					$value = $doc->createTextNode($l['hits']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$tags = $doc->createElement('Tags');
					$error= $link->appendChild($tags); 
					foreach($l['tags'] as $m){
						$link_tags = $doc->createElement('Tag');
						$error= $tags->appendChild($link_tags);
						$value = $doc->createTextNode($m);
						//if($verbose ==1){echo $value;echo'<br />';}
						$value = $error->appendChild($value);
					}
				}
			}
		}
		echo $doc->saveXML();
		die;
	}		
?>